package cn.stylefeng.guns.modular.transport.utils;

import cn.stylefeng.guns.modular.transport.model.result.MapDisptchResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 高德猎鹰轨迹工具类
 */
@Component
public class MapTrackUtils {

    // 蜀能key 4bb7b6534a7dd0bee729aa6d42e1f1f2
    // like的key 7dcc341a969e116364b64dfb6bca1d90

    private static final String API_KEY = "4bb7b6534a7dd0bee729aa6d42e1f1f2";

    private final RestTemplate restTemplate;

    public MapTrackUtils(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 发送get请求
     */
    public String sendGetRequest(String url, Map<String, String> params) {
        StringBuilder builder = new StringBuilder(url);
        if (params != null && !params.isEmpty()) {
            builder.append("?");
            params.forEach((key, value) -> {
                if (!StringUtils.isEmpty(value)) {
                    builder.append(key).append("=").append(value).append("&");
                }
            });
            builder.deleteCharAt(builder.length() - 1);
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(builder.toString(), HttpMethod.GET, entity, String.class);
        return response.getBody();
    }

    /**
     * 发送post请求
     */
    public String sendPostRequest(String url, Object requestBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url + "?key=" + API_KEY, entity, String.class);
        return response.getBody();
    }

    // 创建轨迹服务
    public String createTrackService(String name, String desc) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("name", name);
        params.put("desc", desc);
        return sendPostRequest(MapConst.SERVICE_ADD_URL, params);
    }

    // 删除轨迹服务
    public String delTrackService(String sid) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        return sendPostRequest(MapConst.SERVICE_DELETE_URL, params);
    }

    // 更新轨迹服务
    public String updateTrackService(String sid, String name, String desc) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("name", name);
        params.put("desc", desc);
        return sendPostRequest(MapConst.SERVICE_UPDATE_URL, params);
    }

    // 查询轨迹服务
    public String queryTrackServiceList() {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        return sendGetRequest(MapConst.SERVICE_LIST_URL, params);
    }

    // 创建终端
    public String createTerminal(String sid, String name, String desc) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("name", name);
        params.put("desc", desc);
        return sendPostRequest(MapConst.TERMINAL_ADD_URL, params);
    }

    // 删除终端
    public String delTerminal(String sid, String tid) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        return sendPostRequest(MapConst.TERMINAL_DELETE_URL, params);
    }

    // 更新终端
    public String updateTerminal(String sid, String tid, String name, String desc) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("name", name);
        params.put("desc", desc);
        return sendPostRequest(MapConst.TERMINAL_UPDATE_URL, params);
    }

    // 查询终端列表
    public String queryTerminals(String sid, String tid, String name, Integer page) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("name", name);

        Optional.ofNullable(page).ifPresent(p -> params.put("page", p.toString()));
        return sendGetRequest(MapConst.TERMINAL_LIST_URL, params);
    }

    // 创建轨迹
    public String createTrace(String sid, String tid, String trname) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trname", trname);
        return sendPostRequest(MapConst.TRACE_ADD_URL, params);
    }

    // 删除轨迹
    public String delTrace(String sid, String tid, String trid) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trid", trid);
        return sendPostRequest(MapConst.TRACE_DELETE_URL, params);
    }

    // 查询轨迹信息
    public String queryTrackInfo(String sid, String tid, String trid, String startTime, String endTime, String correction, Integer recoup, Integer gap, Integer ispoints, Integer page, Integer pagesize) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trid", trid);
        params.put("correction", correction);
        // 对为null使用Optional.ofNullable的处理
        Optional.ofNullable(startTime).ifPresent(s -> params.put("starttime", s));
        Optional.ofNullable(endTime).ifPresent(e -> params.put("endtime", e));
        Optional.ofNullable(recoup).ifPresent(r -> params.put("recoup", r.toString()));
        Optional.ofNullable(gap).ifPresent(g -> params.put("gap", g.toString()));
        Optional.ofNullable(ispoints).ifPresent(i -> params.put("ispoints", i.toString()));
        Optional.ofNullable(page).ifPresent(p -> params.put("page", p.toString()));
        Optional.ofNullable(pagesize).ifPresent(ps -> params.put("pagesize", ps.toString()));
        return sendGetRequest(MapConst.TERMINAL_TRSEARCH_URL, params);
    }

    // 上传轨迹点
    public String uploadTracePoint(String sid, String tid, String trid, String points) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trid", trid);
        params.put("points", points);
        return sendPostRequest(MapConst.POINT_UPLOAD_URL, params);
    }

    // 查询终端实时位置
    public String queryTerminalLocation(String sid, String tid, String trid, boolean correction) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("tid", tid);
        params.put("trid", trid);
        params.put("correction", correction ? "driving" : "n");
        return sendGetRequest(MapConst.TERMINAL_LASTPOINT_URL, params);
    }

    // 关键字搜索终端
    public String queryTerminalByKeyword(String sid, String keywords,String filter,String sortrule,Integer page,Integer pageSize) {
        Map<String, String> params = new HashMap<>();
        params.put("key", API_KEY);
        params.put("sid", sid);
        params.put("keywords", keywords);
        params.put("filter", filter);
        params.put("sortrule", sortrule);

        Optional.ofNullable(page).ifPresent(p -> params.put("page", p.toString()));
        Optional.ofNullable(pageSize).ifPresent(ps -> params.put("pagesize", ps.toString()));
        return sendGetRequest(MapConst.TERMINAL_SEARCH_URL, params);
    }

}
